﻿/* Copyright 2009 dnAnalytics Project.
 *
 * Contributors to this file:
 * Marcus Cuda
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 * 
 * * Redistributions of source code must retain the above copyright notice, this 
 *   list of conditions and the following disclaimer.
 * * Redistributions in binary form must reproduce the above copyright notice, 
 *   this list of conditions and the following disclaimer in the documentation
 *   and/or other materials provided with the distribution.
 * * Neither the name of the dnAnalytics Project nor the names of its contributors
 *   may be used to endorse or promote products derived from this software without
 *   specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
using System;
using System.Collections.Generic;
using System.Threading;

namespace dnAnalytics.Threading
{
    //Code from Math.NET Numerics by Christoph Rüegg
    internal static class ThreadQueue
    {
        /// <summary>
        /// Sync Object for the thread queue state.
        /// </summary>
        private static readonly object _stateSync = new object();

        /// <summary>
        /// Sync Object for queue access (to be sure it's used by us only).
        /// </summary>
        private static readonly object _queueSync = new object();

        /// <summary>
        /// Maximum number of jobs that can be in the queue at the same time. 
        /// </summary>
        private const int _maximumQueueLength = 1024;

        /// <summary>
        /// Counting Semaphore to make the worker thread wait for jobs
        /// </summary>
        private static Semaphore _tasksAvailableSemaphore;

        /// <summary>
        /// Queue holding the pending jobs.
        /// </summary>
        private static readonly Queue<Task> _queue = new Queue<Task>();

        /// <summary>
        /// Running flag, used to signal worker threads to stop cleanly.
        /// </summary>
        private static bool _running = true;

        /// <summary>
        /// Worker threads
        /// </summary>
        private static Thread[] _threads;

        /// <summary>
        /// Number of worked threads.
        /// </summary>
        internal static int ThreadCount { get; private set; }

        /// <summary>
        /// Static Constructor
        /// </summary>
        static ThreadQueue()
        {
            Start(Control.ThreadCount);
        }

        /// <summary>
        /// Add a job to the queue.
        /// </summary>
        /// <param name="task">The job to run.</param>
        internal static void Enqueue(Task task)
        {
            if (!_running)
            {
                Start();
            }

            lock (_queueSync)
            {
                _queue.Enqueue(task);
            }

            _tasksAvailableSemaphore.Release();
        }

        /// <summary>
        /// Add a set of jobs to the queue.
        /// </summary>
        /// <param name="tasks">The jobs to run.</param>
        internal static void Enqueue(IList<Task> tasks)
        {
            if (!_running)
            {
                Start();
            }

            lock (_queueSync)
            {
                foreach (var task in tasks)
                {
                    _queue.Enqueue(task);
                }
            }

            _tasksAvailableSemaphore.Release(tasks.Count);
        }

        /// <summary>
        /// Worker Thread Program
        /// </summary>
        private static void WorkerThreadStart()
        {
            while (_running)
            {
                // Wait until a job is available, or we should shut down
                _tasksAvailableSemaphore.WaitOne();

                // Check whether we should shut down
                if (!_running)
                {
                    _tasksAvailableSemaphore.Release();
                    break;
                }

                // Get the job...
                Task task = null;
                lock (_queueSync)
                {
                    if (_queue.Count > 0)
                    {
                        task = _queue.Dequeue();
                    }
                }

                // ...and run it
                if (task != null)
                {
                    task.Compute();
                    task.Set();
                }
            }
        }

        internal static void Start(int numberOfThreads)
        {
            lock (_stateSync)
            {
                if (_threads != null)
                {
                    if (_threads.Length == numberOfThreads)
                    {
                        return;
                    }

                    Shutdown();
                }

                ThreadCount = numberOfThreads;
                Start();
            }
        }

        internal static void Start()
        {
            lock (_stateSync)
            {
                if (_threads != null)
                {
                    return;
                }

                _tasksAvailableSemaphore = new Semaphore(_queue.Count, _maximumQueueLength);
                _running = true;
                _threads = new Thread[ThreadCount];

                for (var i = 0; i < _threads.Length; i++)
                {
                    _threads[i] = new Thread(WorkerThreadStart)
                    {
                        IsBackground = true
                    };

                    _threads[i].Start();
                }
            }
        }

        internal static void Shutdown()
        {
            lock (_stateSync)
            {
                if (_threads == null)
                {
                    return;
                }

                // try to stop the worker threads cleanly
                _running = false;
                _tasksAvailableSemaphore.Release();

                // wait until all threads have stopped
                foreach (var thread in _threads)
                {
                    thread.Join();
                }

                _tasksAvailableSemaphore.Close();
                _tasksAvailableSemaphore = null;
                _threads = null;
            }
        }
    }
}